import { getDomain } from "../lib/scripts/common.js";

/**
 * 划词翻译功能的实现
 * 需要对页面的相关事件进行监听，根据用户设定来决定是否进行监听。
 */
chrome.storage.sync.get("OtherSettings", function(result) {
    var OtherSettings = result.OtherSettings;
    if (OtherSettings && OtherSettings["SelectTranslate"]) {
        document.addEventListener("mouseup", mouseUpHandler);
        document.addEventListener("mousedown", disappearButton);
    }
    if (OtherSettings && OtherSettings["TranslateAfterDblClick"]) {
        document.addEventListener("dblclick", dblClickHandler);
    }
});

/**
 * 当用户更改设定时添加或删除事件监听。
 */
chrome.storage.onChanged.addListener(function(changes, area) {
    if (area === "sync" && changes["OtherSettings"]) {
        if (changes["OtherSettings"].newValue["SelectTranslate"]) {
            document.addEventListener("mouseup", mouseUpHandler);
            document.addEventListener("mousedown", disappearButton);
        } else {
            document.removeEventListener("mouseup", mouseUpHandler);
            document.removeEventListener("mousedown", disappearButton);
        }
        if (changes["OtherSettings"].newValue["TranslateAfterDblClick"]) {
            document.addEventListener("dblclick", dblClickHandler);
        } else {
            document.removeEventListener("dblclick", dblClickHandler);
        }
    }
});

/**
 * 创建翻译按钮的图标元素
 */
var translateButton = document.createElement("div");
var disable = true; // 用于实现点击完按钮后按钮消失的功能，用于在某些情况下禁止按钮的显示
var img = document.createElement("img");
img.src =
    "";
translateButton.appendChild(img);
translateButton.id = "translate-button";
translateButton.style.backgroundColor = "white"; // 动态设置样式以兼容Dark Reader
translateButton.style.boxShadow = "0px 0px 2px 2px #ddd"; // 动态设置样式以兼容Dark Reader
document.documentElement.appendChild(translateButton);
translateButton.addEventListener("mousedown", translateSubmit);

/**
 * Handle double click event
 */
function dblClickHandler() {
    executeIfNotInBlacklist(function() {
        var selection = window.getSelection();
        if (selection.toString().trim()) {
            // 检查页面中是否有内容被选中
            chrome.storage.sync.get("OtherSettings", function(result) {
                var OtherSettings = result.OtherSettings;
                // Show translating result instantly.
                if (
                    OtherSettings &&
                    !OtherSettings["TranslateAfterSelect"] &&
                    OtherSettings["TranslateAfterDblClick"]
                ) {
                    disable = false;
                    translateSubmit();
                }
            });
        } else {
            translateButton.style.display = "none"; // 使翻译按钮隐藏
        }
    });
}

/**
 * Handle mouse up event.
 */
function mouseUpHandler(event) {
    executeIfNotInBlacklist(function() {
        var selection = window.getSelection();
        if (selection.toString().trim()) {
            // 检查页面中是否有内容被选中
            chrome.storage.sync.get("OtherSettings", function(result) {
                var OtherSettings = result.OtherSettings;
                // Show translating result instantly.
                if (OtherSettings && OtherSettings["TranslateAfterSelect"]) {
                    translateSubmit();
                    // Show translate button.
                } else if (disable) {
                    setTimeout(function() {
                        showButton(event);
                    }, 0);
                }
            });
        } else {
            translateButton.style.display = "none"; // 使翻译按钮隐藏
        }
    });
}

/**
 * 当鼠标选中一段文字后，调用此函数，显示出翻译按钮
 */
function showButton(event) {
    if (disable) {
        // 翻译按钮的纵坐标位置: 鼠标停留位置 + y方向滚动的高度 + bias
        translateButton.style.top = event.y + document.documentElement.scrollTop - 55 + "px";
        // 翻译按钮的横坐标位置: 鼠标停留位置 + x方向滚动的高度 + bias
        translateButton.style.left = event.x + document.documentElement.scrollLeft + 10 + "px";
        // 使翻译按钮显示出来
        translateButton.style.display = "inline-block";
    }
}

/**
 * 处理点击翻译按钮后的事件
 */
function translateSubmit() {
    disable = false; // 禁止按钮显示
    // 发送消息给后台进行翻译。
    if (
        window
            .getSelection()
            .toString()
            .trim()
    ) {
        chrome.runtime.sendMessage(
            {
                type: "translate",
                text: window.getSelection().toString()
            },
            function() {
                translateButton.style.display = "none";
            }
        );
    }
}

/**
 * 如果页面中没有鼠标选中的区域，调用此函数去掉翻译按钮
 */
function disappearButton() {
    var selection = window.getSelection();
    setTimeout(function() {
        if (!selection.toString().trim()) {
            translateButton.style.display = "none";
            disable = true; // 回复按钮显示
        }
    }, 100);
    setTimeout(function() {
        if (!selection.toString().trim()) {
            translateButton.style.display = "none";
            disable = true; // 回复按钮显示
        }
    }, 400);
}

/**
 * 如果当前页面不在黑名单中则执行给定的回调函数。
 *
 * @param {Function} callback 回调
 */
function executeIfNotInBlacklist(callback) {
    chrome.storage.sync.get("blacklist", function(result) {
        var url = window.location.href;
        var blacklist = result.blacklist;
        if (!blacklist || (!blacklist.domains[getDomain(url)] && !blacklist.urls[url])) {
            callback();
        }
    });
}

/**
 *  实现快捷键翻译
 */
chrome.runtime.onMessage.addListener(function(message, sender, callback) {
    if (!sender || !sender.tab) {
        switch (message.type) {
            case "command":
                switch (message.command) {
                    case "translate_selected":
                        translateSubmit();
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }

        if (callback) {
            callback();
        }
        return true;
    }
});
